package com.hmkj.web.controller.my;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.constant.ConfigNID;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.amount.AccountModel;
import com.hmkj.core.model.user.UserModel;
import com.hmkj.core.po.amount.Account;
import com.hmkj.core.po.user.User;
import com.hmkj.core.po.user.UserBank;
import com.hmkj.core.po.user.UserFreeze;
import com.hmkj.core.service.amount.AccountService;
import com.hmkj.core.service.amount.CashService;
import com.hmkj.core.service.amount.RechargeService;
import com.hmkj.core.service.user.UserBankService;
import com.hmkj.core.service.user.UserFreezeService;
import com.hmkj.core.service.user.UserService;
import com.hmkj.web.controller.GenericController;
import com.xiaoleilu.hutool.util.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ......................我佛慈悲......................
 * ......................_oo0oo_.......................
 * .....................o8888888o......................
 * .....................88" . "88......................
 * .....................(| -_- |)......................
 * .....................0\  =  /0......................
 * ...................___/`---'\___....................
 * ..................' \\|     |// '...................
 * ................/ \\|||  :  |||// \.................
 * .............../ _||||| -卍-|||||- \................
 * ..............|   | \\\  -  /// |   |...............
 * ..............| \_|  ''\---/''  |_/ |...............
 * ..............\  .-\__  '-'  ___/-. /...............
 * ............___'. .'  /--.--\  `. .'___.............
 * .........."" '<  `.___\_<|>_/___.' >' ""............
 * ........| | :  `- \`.;`\ _ /`;.`/ - ` : | |.........
 * ........\  \ `_.   \_ __\ /__ _/   .-` /  /.........
 * ....=====`-.____`.___ \_____/___.-`___.-'=====......
 * ......................`=---='.......................
 * ....................................................
 * .................佛祖开光 ,永无BUG...................
 */
@Api(description = "账户资金相关")
@Slf4j
@RestController
@RequestMapping(GenericController.MEMBER_URL + "/account")
public class MyAccountController extends GenericController<Integer, User> {
    @Resource
    private UserService userService;
    @Resource
    private UserBankService userBankService;
    @Resource
    private RechargeService rechargeService;
    @Resource
    private AccountService accountService;
    @Resource
    private CashService cashService;
    @Resource
    private UserFreezeService userFreezeService;

    @ApiOperation(value = "获取用户账户相关信息", notes = "获取用户账户相关信息")
    @ResponseBody
    @RequestMapping(value = "getAccountInfo", method = RequestMethod.POST)
    public ResultEntity<AccountModel> getAccountInfo() {
        return ok(accountService.getAccountModel(getLoginUser().getId()));
    }

    /**
     * 出金检测
     * 0.查询用户冻结信息，如果出金功能被冻结，则提示用户。
     * 1.查询用户认证信息，如果用户没有实名认证，则提示用户先进行实名认证
     * 2.查询当前用户绑定的银行卡列表，如果为空，则提示用户绑卡
     * 3.查询用户的提现密码是否，设置了，如果没有设置，提示用户设置
     * 4.查询当前登录用户类型，如果为 综合会员则，需要显示其保证金账户
     */
    @ApiOperation(value = "出金检测", notes = "出金检测")
    @ResponseBody
    @RequestMapping(value = "/checkCash", method = RequestMethod.POST)
    public ResultEntity checkCash() throws Exception {
        User user = userService.selectByPrimaryKey(getLoginUser().getId());
        UserFreeze freeze = userFreezeService.selectOne(new UserFreeze(uf -> {
            uf.setUserId(user.getId());
        }));
        //0.查询用户冻结信息，如果出金功能被冻结，则提示用户。
        if (freeze.getFreezeCash() == UserFreeze.STATUS.T2.code) {
            throw new BussinessException("出金功能被冻结，请联系客服");
        }
        //1.查询用户认证信息，如果用户没有实名认证，则提示用户先进行实名认证
        if (StringUtils.isBlank(user.getRealName()) || StringUtils.isBlank(user.getIdCard())) {
            throw new BussinessException("您还没有进行实名认证");
        }
        // 用户绑定的银行卡列表
        List<UserBank> userBankList = userBankService.select(new UserBank(ub -> {
            ub.setUserId(user.getId());
            ub.setDelFlag(UserBank.DELFLAG.NORMAL.code);
        }));
        if (CollectionUtil.isEmpty(userBankList)) {
            throw new BussinessException("您还没有绑卡，请立即绑卡");
        }
        if (StringUtils.isBlank(user.getPayPassword())) {
            throw new BussinessException("您的出金密码还没有设置");
        }
        Map<String, Object> data = new HashMap<>();
        return ok("出金检测成功", data);
    }


    /**
     * 出金操作
     */
    @ApiOperation(value = "出金操作", notes = "出金操作")
    @ResponseBody
    @RequestMapping(value = "/doCash", method = RequestMethod.POST)
    public ResultEntity doCash(@ApiParam("银行卡id") @RequestParam String bankCardId, @ApiParam("提现金额") @RequestParam BigDecimal money, @ApiParam("出金密码(rsa加密再base64加密)") @RequestParam String cashPasswd) throws Exception {
        User user = userService.selectByPrimaryKey(getLoginUser().getId());
        String result = checkParam(bankCardId, money, cashPasswd, user);
        if (result != null) {
            throw new BussinessException(result);
        }

        cashService.createCash(bankCardId, money, user);
        return ok("出金成功等待审核");
    }


    private String checkParam(String bankCardId, BigDecimal money, String cashPasswd, User user) {
        String result = null;
        BigDecimal cashMin = redisService.get(ConfigNID.CASH_MIN, BigDecimal.class);
        BigDecimal cashMax = redisService.get(ConfigNID.CASH_MAX, BigDecimal.class);
        Account account = accountService.selectOne(new Account(a -> {
            a.setUserId(user.getId());
            a.setDelFlag(Account.DELFLAG.NORMAL.code);
        }));
        if (StringUtils.isBlank(bankCardId)) {
            result = "没有选择出金银行卡";
        } else if (cashMin != null && money.compareTo(cashMin) < 0) {
            result = "出金金额不能小于" + cashMin;
        } else if (cashMax != null && money.compareTo(cashMax) > 0) {
            result = "出金金额不能大于" + cashMax;
        } else if (StringUtils.isBlank(cashPasswd)) {
            result = "出金密码不能为空";
        } else if (null == account) {
            result = "账户异常";
        } else if (money.compareTo(account.getAvailable()) > 0) {
            result = "出金金额不能大于可用余额";
        } else if (!user.getPayPassword().equals(UserModel.encodePwd(UserModel.staticDecryptPwd(cashPasswd)))) {
            result = "出金密码错误";
        }
        return result;
    }


}
